<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Jobs\SaveSysLogController;
use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
	
	/**
	 * 权限验证
	 * @param user_id 用户id
	 * @param identity 权限标识数组 array('order_add', 'order_update', 'trip_update')
	 */
	public function powers($data){
		$identity = "'".implode("','", $data['identity'])."'";
		$sql = "select pr.*
				       from xt_role_user_join ruj
				       left join (select prj.role_id, prj.power_id, p.*
				                         from xt_powers_role_join prj
				                         inner join xt_powers p on p.Id=prj.power_id
				                  ) as pr on pr.role_id = ruj.role_id
				       where ruj.user_id={$data['user_id']} and pr.identity in ({$identity})
				       group by pr.power_id";
		$power_list = json_decode(json_encode(db::select($sql)), true);
		
		$array = array();
		foreach ($power_list as $k=>$v){
			$array[] = $v['identity'];
		}
		
		$powers = array();
		foreach ($data['identity'] as $va){
			if(in_array($va, $array)){
				$powers[$va] = true;
			}else{
				$powers[$va] = false;
			}
		}
		return $powers;
		
	}
	
	/**
	 * desc:返回数据
	 * @param $desc(描述)
	 * @param int $code(状态码)
	 * @param array $data(数据)
	 */
	public function back($desc,$code='500',$data=''){
		$back['code'] = (string)$code;
		$back['desc'] = $desc;
		if((!empty($data)) or is_array($data)){
			$back['data'] = $data;
		}
		
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($back, JSON_UNESCAPED_UNICODE));
	}
 
////////////////////////////////////// Api验签
	/**
	 * @desc 验证签名及是否过期
	 * @param $data 调用参数
	 * @param method 调用方法名
	 * @param nonce 随机字符串
	 * @param timestamp 时间戳（调用时的时间戳）
	 * @param sign 签名
	 * @return int:1->验签通过,0->验签失败,2->超时,3->重复使用
	 */
	public function check_sign($data){
		if(empty($data['method'])){
			$this->back('无调用方法名');
		}else if(empty($data['nonce'])){
			$this->back('无随机字符串');
		}else if(empty($data['timestamp'])){
			$this->back('无时间戳');
		}else if(empty($data['sign'])){
			$this->back('无签名');
		}
		
		////是否超时     5分钟
		$signTime = time() - (int)$data['timestamp'];
		if($signTime > 60*5){
			$this->back('时间超时');
		}
		
		////验签
		$sql = "select appid,secretkey from `config`";
		$config = json_decode(json_encode(db::select($sql)),true);
		
		$arr = array();
		$arr['appid'] = $config[0]['appid'];
		$arr['secretkey'] = $config[0]['secretkey'];
		$arr['method'] = $data['method'];
		$arr['nonce'] = $data['nonce'];
		$arr['timestamp'] = $data['timestamp'];
		$newsign = $this->sign($arr);
		if($data['sign'] != $newsign){
			$this->back('验签失败');
		}
		
		////随机字符串是否重复使用
		$sql = "select `Id`
					from request_record
					where nonce='{$data['nonce']}'";
		$rr = DB::select($sql);
		if($rr){
			exit($this->back('重复使用'));
		}
		
		//删除请求记录     大于5分钟
		$sql = "delete from request_record where create_time<" .(time()-60*5);
		db::delete($sql);
		
		//新增请求记录
		$sql = "insert into request_record(`nonce`,`create_time`)
						values('{$data['nonce']}',{$data['timestamp']})";
		db::insert($sql);
		
	}
	
	/**
	 * 生成验签
	 * @param $data（验签数据）
	 */
	public function sign($data){
		//第一步：参数名ASCII码从小到大排序（字典序）
		ksort($data);
		
		$string = '';
		foreach ($data as $k => $v){
			if($k != "sign" && $v != "" && !is_array($v)){
				$string .= $k . "=" . $v . "&";
			}
		}
		
		$string = trim($string, "&");
		$sign = md5($string);
		return $sign;
	}
	
	
	public function GetUserIdByToken($token){
		$users = db::table('users')->where('token',$token)->first();
		$user_id = 0;
		 if($users){
		   $user_id = $users->Id;
		 }
		 return $user_id;
	  }
    
	public function AddSysLog($params,$result,$name='',$function=''){
		$token = $params['token']??'';
        $addsyslog['user_id'] = $this->GetUserIdByToken($token);
        $addsyslog['create_time'] = date('Y-m-d H:i:s',time());
		$addsyslog['input'] = json_encode($params);
        // $addsyslog['input'] =  $this->cut_str(json_encode($params),10000);
        $addsyslog['function'] = $function;
        // $addsyslog['output'] = $this->cut_str(json_encode($result),10000);
		$addsyslog['output'] = json_encode($result);
        $addsyslog['name'] = $name;
//		db::table('sys_log')->insert($addsyslog);
        // $insert['user_id'] = $params['user_id'];
        // $insert['function'] = $params['function'];
        // $insert['name'] = $params['name'];
        // $insert['input'] = $params['input'];
        // $insert['output'] = $params['output'];
        // $insert['create_time'] = $params['create_time'];
        // 加入队列
         $job = new SaveSysLogController();
         $job::runJob($addsyslog);
	}


	public function cut_str($str,$len,$suffix="..."){
		if(strlen($str) > $len){
			if(function_exists('mb_substr')){
					$str = mb_substr($str,0,$len,'utf-8').$suffix;
			}else{
					$str= substr($str,0,$len,'utf-8').$suffix;
			}     
		} 
		return $str; 
	}

}//
